package com.xyz.service.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.xyz.dto.CartDTO;
import com.xyz.enums.ProductStatusEnum;
import com.xyz.enums.ResultEnum;
import com.xyz.exception.SellException;
import com.xyz.pojo.ProductInfo;
import com.xyz.repository.ProductInfoRepository;
import com.xyz.service.ProductService;

@Service
public class ProductServiceImpl implements ProductService {

	@Autowired
	private ProductInfoRepository productInfoRepository;

	@Override
	public ProductInfo findById(String productId) {

		return productInfoRepository.findById(productId).get();

	}

	/**
	 * @desc 分页查询所有商品信息
	 */
	@Override
	public List<ProductInfo> findUpAll() {

		return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
	}

	@Override
	public Page<ProductInfo> findAll(Pageable pageable) {

		return productInfoRepository.findAll(pageable);
	}

	@Override
	public ProductInfo save(ProductInfo productInfo) {

		return productInfoRepository.save(productInfo);
	}

	/**
	 * 加库存
	 */
	@Override
	public void increaseStock(List<CartDTO> cartDTOList) {

	}

	/**
	 * 减库存
	 */
	@Transactional
	public void decreaseStock(List<CartDTO> cartDTOList) {
		for (CartDTO cartDTO : cartDTOList) {
			ProductInfo productInfo = productInfoRepository.findById(cartDTO.getProductId()).get();
			if (null == productInfo) {
				throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
			}
			//减库存
			Integer result = productInfo.getProductStock() - cartDTO.getProductQuantity();
			if(result < 0) {
				//库存不足
				throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
			}
			productInfo.setProductStock(result);
			
			productInfoRepository.save(productInfo);
		}
	}
	

}
